package com.yun.pano.offline;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.InputFilter;
import android.webkit.JavascriptInterface;
import android.webkit.PermissionRequest;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.easylive.app.service.MediaService;

import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

//    public XWalkView mWebview;
    public WebView mWebview;
    public String baseUri = "https://nav.itomx.cn/pc/dist/#?id=";
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(MainActivity.this, "启动电子导览", Toast.LENGTH_SHORT).show();
        initWebviewSetting();

        try{
//            this.baseUri  = "http://guide4.daokeyun.com";
//            mWebview.loadUrl(this.baseUri);

            final String tmp_filename = "daolan_sid.txt";
            String cacheStr = this.readFile(tmp_filename);
            if(!cacheStr.isEmpty()) {
                this.baseUri += getSid(cacheStr);
                this.baseUri +="&lost_time="+(new Date().getTime());
                Toast.makeText(MainActivity.this, this.baseUri, Toast.LENGTH_LONG).show();
                mWebview.loadUrl(this.baseUri);

                startMediaModule();
            }
            else {
                final EditText inputServer = new EditText(this);
                inputServer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("输入景区ID").setView(inputServer);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String _sign = inputServer.getText().toString();
                        if(_sign!=null && !_sign.isEmpty())
                        {
                            MainActivity.this.saveData(tmp_filename, _sign);
                            Toast.makeText(MainActivity.this, "配置完成，请退出后重新进入！", Toast.LENGTH_LONG).show();
                        }
                        else
                        {
                            mWebview.loadUrl(MainActivity.this.baseUri);
                        }
                    }
                });
                builder.show();
            }

        }
        catch (Exception e) {
            System.out.print(e.getMessage());
        }

    }

    private void startMediaModule(){
        Intent intent = new Intent(this, MediaService.class);
        startService(intent);
    }

    @JavascriptInterface
    public void webCallMediaPlayer(){
        startMediaModule();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mWebview.onDestroy();
    }


    /**
     * 初始化webview setting
     */
    public void initWebviewSetting() {
        mWebview = findViewById(R.id.web);
        mWebview.getSettings().setJavaScriptEnabled(true);
        mWebview.getSettings().setDomStorageEnabled(true);
        mWebview.getSettings().setLoadsImagesAutomatically(true);
//        mWebview.getSettings().setAppCacheEnabled(true);//是否使用缓存
        mWebview.getSettings().setDomStorageEnabled(true);//开启本地DOM存储
        mWebview.getSettings().setLoadsImagesAutomatically(true); // 加载图片
//        mWebview.getSettings().setMediaPlaybackRequiresUserGesture(false);//播放音频，多媒体需要用户手动？设置为false为可自动播放
        mWebview.getSettings().setBlockNetworkImage(false);//不阻塞网络图片
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            允许混合（http，https）
//            websettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            mWebview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                super.onReceivedSslError(view, handler, error);
                handler.proceed();
            }
        });

        mWebview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onPermissionRequest(PermissionRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    //直接同意即可     deny是拒绝
                    request.grant(request.getResources());
                }
            }
        });

        //web page use window.Andoird.webCallMediaPlayer() in JS to start media player.
        mWebview.getSettings().setUserAgentString("Android");
        mWebview.addJavascriptInterface(this,"Android");
    }

    /**
     * 获取景区ID
     * @param str
     * @return
     */
    public String getSid(String str) {
        try{
            JSONObject object = new JSONObject(str);
            return  object.optString("sid");
        }
        catch (Exception exception) {

        }
        return "";
    }

    /**
     * 写配置文件
     * @param filename
     * @param sid
     */
    public void saveData(String filename, String sid) {
        try{
            //get sn
            String sn = getDeviceSN();
            String data = "{\"sn\":\"" + sn +
                    "\", \"sid\":\"" + sid +
                    "\" }";
            writeFile(filename, data);
        }
        catch (Exception exception) {

        }
    }


    /**
     * 获取
     * @return
     */
    public static String getDeviceSN1(){
        String serial = null;
        try {
            Class<?> c =Class.forName("android.os.SystemProperties");
            Method get =c.getMethod("get", String.class);
            serial = (String)get.invoke(c, "ro.serialno");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serial;
    }


    public static String getDeviceSN(){
        String serial = null;
        try {
            serial = UUID.randomUUID().toString();
            System.out.println("系统系统sn"+serial);

            System.out.println("系统sn"+serial);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("系统异常"+e.getMessage());
        }
        return serial;
    }

    //写数据
    public void  writeFile(String fileName,String writestr) throws IOException{
        try{

            FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);

            byte [] bytes = writestr.getBytes();

            fout.write(bytes);

            fout.close();
        }

        catch(Exception e){
            e.printStackTrace();
        }
    }

    //读数据
    public  String readFile(String fileName) throws IOException {
        String res="";
        try{
            FileInputStream fin = openFileInput(fileName);
            int length = fin.available();
            byte [] buffer = new byte[length];
            fin.read(buffer);
            res = EncodingUtils.getString(buffer, "UTF-8");
            fin.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return res;
    }
}
